package org.asg.dis.controller;

import jakarta.validation.Valid;
import org.asg.dis.model.ApiResponse;
import org.asg.dis.model.User;
import org.asg.dis.request.LoginReq;
import org.asg.dis.request.SignupReq;
import org.asg.dis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
public class AccountController {
    private final UserService userService;

    @Autowired
    public AccountController(UserService userService) {
        this.userService = userService;
    }

    @ResponseBody
    @PostMapping(value = "/api/login", produces = "application/json")
    public ApiResponse<String> login(@Valid @RequestBody LoginReq request, @RequestParam String role){
        System.out.println(request.userId());
        System.out.println(request.password());
        System.out.println("next: String token = userService.login(request.userId(), request.password());");
        String token = userService.login(Long.parseLong(request.userId()), request.password(), role);
        System.out.println("next: return Apiresponse.ok(token)");
        return ApiResponse.ok(token);
    }

    @PostMapping("/api/signup")
    public ApiResponse<String> signup(@Valid @RequestBody SignupReq request){
        //@RequestParam @Pattern(regexp = "^\\S{5,16}$") final String nickname,
        //@RequestParam @Pattern(regexp = "^\\S{5,16}$") final String password,
        //@RequestParam @Pattern(regexp = "^[0-9]{10}$") final String phoneNumber
        User newUser = userService.signup(request.nickname(), request.password(), request.phoneNumber());
        String token = userService.login(newUser.getUserId(), newUser.getPassword(), "User");
        return ApiResponse.ok(token);
    }

    @PostMapping("/logout")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> logout(@RequestHeader(value = "Authorization") String raw) {
        if (raw != null && raw.startsWith("Bearer ")) {
            userService.logout(raw.substring(7));
            return ApiResponse.ok();
        }
        return ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "no token");
    }

    @PostMapping("/api/phone-signup")
    public ApiResponse<String> phoneSignup(@RequestParam String number) {
        return ApiResponse.ok("Phone signup successful!");
        //TODO 实现手机号注册逻辑
    }

    @PutMapping("/edit")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> updateUser(@RequestBody User user) {
        //TODO 修改时验证密码
        userService.updateUser(user);
        return ApiResponse.ok("User information updated successfully!");
    }


    @DeleteMapping("/delete")
    public ApiResponse<String> deleteUser(@RequestParam Long userId) {
        //TODO 账号注销逻辑
        userService.deleteUser(userId);
        return ApiResponse.ok("User deleted successfully!");
    }
}
